package com.kgc.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author：
 * <p>
 * @Date:2021/5/28 17:13
 * <p>
 * @Decription:
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String ,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        // 创建一个模板对象
        RedisTemplate<String ,Object> redisTemplate = new RedisTemplate<>();

        // 设置连接工厂对象
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 借助fastjson的序列化方式
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);

        // 借助String的序列化方式
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key使用String序列化
        redisTemplate.setKeySerializer(stringRedisSerializer);

        // value使用fastjson序列化
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);

//        ObjectMapper om = new ObjectMapper();
//        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//        om.registerModule(new Jdk8Module())
//                .registerModule(new JavaTimeModule())
//                .registerModule(new ParameterNamesModule());

        //设置value的序列化方式为json
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //定制化关于时间格式序列化问题
//        ObjectMapper objectMapper = new ObjectMapper();
//        SimpleModule simpleModule = new SimpleModule();
//        simpleModule.addSerializer(DateTime.class,new JodaDateTimeJsonSerializer());
//        simpleModule.addDeserializer(DateTime.class,new JodaDateTimeJsonDeSerializer());
//        objectMapper.registerModule(simpleModule);

        // hash的key也是用String序列化
        redisTemplate.setHashKeySerializer(stringRedisSerializer);

        // hash的value也是使用fastjson序列化
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);

        // 初始化操作
//        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

}
